import React, { Component } from 'react'
import { Card, Button, Table, Modal, message } from 'antd'

import { APIGetRoleList, APIAddRole, APIUpdateRoleAuth } from '../../api'
import memory from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'
import { formatDate } from '../../utils/dateUtils'
import { PAGE_SIZE } from '../../utils/constants'
import AddForm from './AddForm'
import UpdateAuthForm from './UpdateAuthForm'

export default class Role extends Component {

  state = {
    roles: [],
    role: {},
    isShowAdd: false,
    isShowAuth: false
  }

  initColums = () => {
    this.columns = [
      {
        title: '角色名称',
        dataIndex: 'name'
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        render: formatDate
      },
      {
        title: '授权时间',
        dataIndex: 'auth_time',
        render: formatDate
      },
      {
        title: '授权人',
        dataIndex: 'auth_name'
      },
    ]
  }
  onRow = (role) => {
    return {
      onClick: event => {
        this.setState({role})
      }
    }
  }

  getRoleList = async () => {
    const result = await APIGetRoleList()
    if(result.status === 0) {
      const roles = result.data
      this.setState({roles})
    }
  }

  // 添加角色
  addRole = async () => {
    const result = await APIAddRole(this.name)
    if(result.status === 0) {
      message.success('创建角色成功')
      // this.getRoleList()
      this.setState(state => ({
        roles: [...state.roles, result.data]
      }))
    } else {
      message.error('创建角色失败')
    }
    this.setState({isShowAdd: false})
  }
  // 更新角色权限
  updateRole = async () => {
    const role = {
      _id: this.state.role._id,
      menus: this.menus,
      auth_time: Date.now(),
      auth_name: memory.user.username
    }
    const result = await APIUpdateRoleAuth(role)
    if(result.status === 0) {
      // 如果当前更新的是自己角色的权限，强制退出
      if(role._id === memory.user.role_id) {
        memory.user = {}
        storageUtils.removeUser()
        this.props.history.replace('/login')
        message.info('当前角色权限更改，请重新登录！')
      } else {
        message.success('设置角色权限成功！')
        this.getRoleList()
      }
    } else {
      message.error('设置角色权限失败！')
    }
    this.setState({
      isShowAuth: false
    })
  }

  componentDidMount() {
    this.getRoleList()
  }



  render() {
    const { roles, role, isShowAdd, isShowAuth } = this.state

    this.initColums()
    
    const title = (
      <span>
        <Button 
          type="primary" 
          onClick={() => {
            this.setState({isShowAdd: true})
          }}
        >
          创建角色
        </Button>&nbsp;&nbsp;&nbsp;
        <Button 
          type="primary" 
          disabled={!role._id}
          onClick={() => {
            this.setState({isShowAuth: true})
          }}
        >
          设置角色权限
        </Button>
      </span>
    )

    return (
      <Card title={title}>
        <Table
          rowSelection={{
            type: 'radio', 
            selectedRowKeys:[role._id],
            onSelect: (role) => {
              this.setState({role})
            }
          }}
          bordered
          rowKey="_id"
          dataSource={roles}  
          columns={this.columns}
          pagination={{defaultPageSize: PAGE_SIZE, showQuickJumper: true}}
          onRow={this.onRow}
        />
        <Modal 
          title="添加角色" 
          visible={isShowAdd} 
          onOk={this.addRole} 
          onCancel={() => {
            this.setState({isShowAdd: false})
          }}
        >
          <AddForm 
            setName={name => this.name = name}
          />
        </Modal>
        <Modal 
          title="设置权限" 
          visible={isShowAuth} 
          onOk={this.updateRole} 
          onCancel={() => {
            this.setState({isShowAuth: false})
          }}
        >
          <UpdateAuthForm 
            key={Date.now()}
            role={role}
            getMenus={menus => this.menus = menus}
          />
        </Modal>
      </Card>
    )
  }
}
